package top.leoseven.adminproject.presenter;

import android.content.Context;
import android.os.Environment;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;
import com.lzy.okhttputils.callback.StringCallback;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;
import top.leoseven.adminproject.R;
import top.leoseven.adminproject.modle.AppInfo;
import top.leoseven.adminproject.service.StuHomeWorkInfoService;

/**
 * Created by 10789 on 2018-04-11.
 */

public class StuHomeWorkInfoPresenter {
    private Context context;
    private StuHomeWorkInfoService service;
    private File root=new File(Environment.getExternalStorageDirectory(),"homeworkfile");
    public StuHomeWorkInfoPresenter(Context context, StuHomeWorkInfoService service) {
        this.context = context;
        this.service = service;
        if (!root.exists()) {
            root.mkdirs();
        }
    }
    public void loadFile(final String filePath, final int id){
        new Thread(){
            @Override
            public void run() {
                super.run();
                File f = new File(root, id + ".homework");
                if (!f.exists()) {
                    OkHttpUtils.get(filePath)
                            .execute(new FileCallback() {
                                @Override
                                public void onSuccess(File file, Call call, Response response) {
                                    saveFile(file,id);
                                }

                                @Override
                                public void onError(Call call, Response response, Exception e) {
                                    super.onError(call, response, e);
                                    service.onError(e.getMessage());
                                }
                            });
                }else{
                    readFile(f);
                }
               
            }
        }.start();
    }
    private void updateResult(int id,float resultnum,String resul){

    }
    private void readFile(final File file){
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileInputStream fis=null;
                ByteArrayOutputStream bao=null;
                try {
                    bao=new ByteArrayOutputStream();
                    fis=new FileInputStream(file);
                    int len=0;
                    byte[] buffer=new byte[1024];
                    while (-1!=(len=fis.read(buffer))){
                        bao.write(buffer,0,len);
                    }
                    bao.flush();
                    String s = new String(bao.toByteArray());
                    service.onFileLoadFinish(s);
                } catch (IOException e) {
                    service.onError(e.getMessage());
                }finally {
                    try {
                        if (bao!=null) {
                            bao.close();
                        }
                        if (fis!=null) {
                            fis.close();
                        }

                    } catch (IOException e) {
                       service.onError(e.getMessage());
                    }
                }
            }
        }).start();
    }
    private void saveFile(final File file, final int id) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File f = new File(root, id+".homework");
                FileInputStream fis=null;
                FileOutputStream fos=null;
                ByteArrayOutputStream baos=null;
                try {
                     fis= new FileInputStream(file);
                     fos= new FileOutputStream(f);
                     baos=new ByteArrayOutputStream();
                     int len=0;
                     byte[] buffer=new byte[1024];
                     while(-1!=(len=fis.read(buffer))){
                        fos.write(buffer,0,len);
                        baos.write(buffer,0,len);
                     }
                     fos.flush();
                     baos.flush();
                     String result = new String(baos.toByteArray());
                     service.onFileLoadFinish(result);
                }  catch (IOException e) {
                    service.onError(e.getMessage());
                }finally {
                    try {
                        if (fis!=null) {
                            fis.close();
                        }
                        if (fos!=null){
                            fos.close();
                        }
                        if (baos!=null) {
                            baos.close();
                        }
                    } catch (IOException e) {
                        service.onError(e.getMessage());
                    }
                }
            }
        }).start();
    }
    public void commitResult(String result,float resultnum,int workid){
        String token= AppInfo.getToken();
        String username=AppInfo.getUsername();
        OkHttpUtils.post(AppInfo.SERVER+context.getString(R.string.updateHomeWork))
                .params("token",token)
                .params("teachername",username)
                .params("workid",workid)
                .params("result",result)
                .params("resultnum",resultnum)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        JSONObject obj = JSON.parseObject(s);
                        int code = obj.getIntValue("code");
                        if (code==200) {
                            service.onCommitSuccess();
                        }else{
                            service.onCommitFail(obj.getString("message"));
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        service.onCommitFail(e.getMessage());
                    }
                });
    }
}
